<template>
  <n-scrollbar x-scrollable style="max-height: 100vh">
    <CommonPage show-footer>
      <div style="display: flex">
        <n-form-item label="" path="input" style="margin-top: -30px">
          <div >
            <div style="display: flex; align-items: center; ">
              <span style="width: 87px;">仓库：</span>
              <n-input style="margin-left: 10px;" v-model:value="productInfoValue.name" placeholder=""></n-input>
              <n-button type="primary" style="margin-left: 10px;" size="small" @click="sub">查询仓库</n-button>
              <n-button type="primary" @click="showForm = true" style="margin-left: 12px" size="small">添加仓库</n-button>
              <StoreAdd :show="showForm" @update:show="val => showForm = val" :onClose="handleClose" />
            </div>
          </div>
          <label style="margin-left: 35px; align-self: center;">仓库类型：</label>
          <n-select v-model:value="value" :options="options" />
          <n-button style="--n-width: 70px; margin-left: 10px;" type="primary" size="small" @click="searchByCondition()">筛选</n-button>
          <n-button style="--n-width: 70px; margin-left: 10px;padding: 0" type="primary" size="small" @click="deleteSelectProduct()">删除所选</n-button>
        </n-form-item>
      </div>
      <n-data-table
          remote
          :single-line="false"
          ref="table"
          :columns="columns"
          :data="logList"
          :loading="loading"
          :pagination="paginationReactive"
          :row-key="rowKey"
          :scroll-x="900"
          @update:checked-row-keys="handleCheck"
      />
    </CommonPage>
  </n-scrollbar>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue'
import api from '@/api/admin';
import {useUserStore} from '@/store';
import {useRouter} from 'vue-router';
import {formatDate, formatDateTime} from "@/utils";
import StoreAdd from './components/store-add.vue';

const showForm = ref(false);

const handleClose = () => {
  showForm.value = false;
};
const userStore = useUserStore()
const router = useRouter()
const loading = ref(true)
const logList = ref([])
const range = ref(null)
const options = ref([
  {
    label: '全部',
    value: '全部',
  },
  {
    label: '类型一',
    value: "类型一"
  },
  {
    label: "类型二",
    value: '类型二'
  },
  {
    label: "类型三",
    value: '类型三'
  },
  {
    label: "类型四",
    value: '类型四'
  },
  {
    label: "类型五",
    value: '类型五'
  },
  {
    label: "类型六",
    value: '类型六'
  },
]);
const value = ref("全部")
const checkedRowKeysRef = ref([]);
const handleCheck =(rowKeys)=>{
  checkedRowKeysRef.value = rowKeys;
}
const columns = [
  {
    type: 'selection',
    fixed: 'left',
  },
  {
    key: 'colId',
    title: '序号',
    width: 30,
  },
  {
    key: 'name',
    title: '仓库名称',
    width: 90,
    render(row){
      return formatDateTime(row["optime"])
    }
  },
  {
    key: 'category',
    title: '仓库地址',
    width: 150,
  },
  {
    key: 'attribute',
    title: '仓库类型',
    width: 70,
  },
  {
    key: 'supplier',
    title: '负责人',
    width:70,
  },
  {
    key: 'supplier',
    title: '创建人',
    width:70,
  },
  {
    key: 'status',
    title: '创建时间',
    width: 100,
    align:'left',
  },
]
let total = 0
const paginationReactive = reactive({
  page: 1,
  pageSize: 50,
  showSizePicker: true,
  pageSizes: [50, 100, 150],
  itemCount:0,
  prefix: () => {
    return '查询出 ' + total + '条记录';
  },
  onChange: (page) => {
    paginationReactive.page = page;
    queryByPage()
  },
  onUpdatePageSize: (pageSize) => {
    paginationReactive.pageSize = pageSize;
    paginationReactive.page = 1;
    queryByPage()
  }
});
const productInfoValue = ref({
  name:'',
  id:'',
  pageNum:paginationReactive.page,
  pageSize:paginationReactive.pageSize

});
const deleteSelectProduct = ()=>{
  if(checkedRowKeysRef.value.length <= 0) {
    $message.error("当前并未选择仓库！")
    return
  }
  $dialog.confirm({
    title: '警告',
    content: '您确定删除当前所选仓库？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const ids = checkedRowKeysRef.value.join(",")
      console.log(ids)
      loading.value = true
      try {
        const res = await api.deleteByIds({logIds:ids})
        if(res.code === 200) {
          $message.success("删除所选仓库成功！")
          // await queryByPage()
          await searchByCondition()
        }
        else {
          $message.error(res.message)
        }
      } catch (err) {
        $message.error("删除所选仓库失败！")
      }finally{
        loading.value = false
      }
    },
  })
}
const searchByCondition = async ()=>{
  const type = value.value
  let timeFrom = ""
  let timeTo = ""
  if(range.value !== null) {
    timeFrom = formatDate(range.value[0])
    timeTo = formatDate(range.value[1])
  }
  loading.value = true
  try {
    paginationReactive.page = 1;
    const res = await api.getLogByCondition({
      type,
      timeFrom,
      timeTo,
      pageNum:paginationReactive.page,
      pageSize:paginationReactive.pageSize,
    })
    if(res.code === 200) {
      total = res.data.total
      paginationReactive.itemCount = total
      logList.value = res.data.list.map((item,i)=>{
        return {...item,
          colId: i+1+(paginationReactive.page-1)*paginationReactive.pageSize
        }
      })
      $message.success("获取仓库成功！")
    }
    else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("查询仓库失败！")
  }finally{
    loading.value = false
  }
}
const onDeleteLog = async (log)=>{
  $dialog.confirm({
    title: '警告',
    content: '您确定删除当前仓库？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const {id} = log
      loading.value = true
      try {
        const res = await api.deleteById({id})
        if(res.code === 200) {
          $message.success("删除仓库成功！")
          // await queryByPage()
          await searchByCondition()
        }
        else {
          $message.error(res.message)
        }
      } catch (err) {
        $message.error("删除仓库失败！")
      }finally{
        loading.value = false
      }
    }
  })
}
const onDetailLog = async (log)=>{
  const {id} = log
  await router.push({name: 'AdminLogDetail', params: {logId: id}});
}
const queryByPage = async ()=>{
  loading.value = true
  try {
    const res = await api.getAllLog(
        {
          pageNum:paginationReactive.page,
          pageSize:paginationReactive.pageSize,
        })
    if(res.code === 200) {
      total = res.data.total
      paginationReactive.itemCount = total
      logList.value = res.data.list.map((item,i)=>{
        return {...item,
          colId: i+1
        }
      })
      $message.success("获取仓库成功！")
    }
    else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取仓库失败！")
  }finally{
    loading.value = false
  }
}
const rowKey = (rowData) => {
  return rowData.id
}
onMounted(()=>{
  queryByPage()
})
</script>
<style scoped>
:deep(.n-data-table-th__title),
:deep(.n-data-table-td) {
  text-align: center;

}
:deep(.n-select) {
  width: 140px !important;
}

:deep(.two-line-description) {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2; /* 控制显示的行数 */
  overflow: hidden;
}

</style>
